package com.jy.api.service.impl;

import com.jy.api.dao.IpStoreAddressDao;
import com.jy.api.dao.ProductDao;
import com.jy.api.domain.IpStoreAddress;
import com.jy.api.domain.Product;
import com.jy.api.service.IpStoreAddressService;
import com.jy.api.signUpReq.IpAddressReq;
import com.jy.api.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xiaohua on 2019/5/29.
 */
@Service
public class IpStoreAddressServiceImpl implements IpStoreAddressService {
    @Autowired
    private IpStoreAddressDao addressDao;
    @Autowired
    private ProductDao productDao;


    @Override
    @Transactional
    public Result mergeIpAddress(IpAddressReq req) {
        IpStoreAddress address;
        if (req.getId() == 0) {
            address = new IpStoreAddress(req);
        } else {
            address = addressDao.findOne(req.getId());
            address.setIpAddress(req.getIpAddress());
            address.setName(req.getName());
            address.setPort(req.getPort());
            List<Product> list = productDao.findByIpIdAndEnabled(req.getId(), true);
            for (Product p : list) {
                p.setIpName(req.getName());
                p.setPort(req.getPort());
            }
            productDao.save(list);
        }
        addressDao.save(address);
        return new Result(200, "修改成功");
    }

    @Override
    public Result deleteByIpId(IpAddressReq req) {
        IpStoreAddress storeAddress = addressDao.findOne(req.getId());
        Result result;
        if (null != storeAddress) {
            List<Product> list = productDao.findByIpIdAndEnabled(req.getId(), true);
            if (list.isEmpty()) {
                storeAddress.setEnabled(false);
                addressDao.save(storeAddress);
                result = new Result(200, "修改成功");
            } else {
                result = new Result(400, "该Ip地址已有商品使用，请核实后进行删除");
            }

        } else {
            result = new Result(400, "该ip地址不存在，请核实");
        }

        return result;
    }
}
